﻿Namespace PL.MetaSDK 'Processing Layer

    Public Class MetaStrings_PL
        Inherits PLBase
        Implements IPLProcess

        Public Property SequenceGeneration As Boolean = True

        Public Sub New()
            MyBase.New()
        End Sub


        Public Sub New(ByVal queryName As String)
            MyBase.New(queryName)
        End Sub

        Public Overrides Function Delete() As Boolean
            Return True
        End Function

        Public Overrides Function Validate() As Boolean
            Return True
        End Function

        ''' <summary>
        ''' 
        ''' </summary>
        ''' <param name="stringID"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function ExportMetaStrings(ByVal filename As String, ByVal stringID As Guid) As Boolean
            Using ms As MetaStrings_PL = New MetaStrings_PL("MetaStringsExport")
                Try
                    ms.MetaDataTable.GetMetaCommand()
                    ms.MetaDataTable.MetaCommand.SQLWhere = String.Format("StringID = '{0}'", stringID)
                    ms.InitDataForExport()
                    ms.Dataset.DataSetName = stringID.ToString
                    ms.Dataset.WriteXml(filename, XmlWriteMode.WriteSchema)
                    Return True
                Catch ex As Exception
                    Throw ex
                End Try
                Return False
            End Using
        End Function

        Public Shared Function ExportMetaStringsToMaster(ByVal stringID As Guid) As Boolean
            Dim IsSaved As Boolean
            Using mcSource As MetaStrings_PL = New MetaStrings_PL("MetaStringsExport")
                Try
                    mcSource.MetaDataTable.GetMetaCommand()
                    mcSource.MetaDataTable.MetaCommand.SQLWhere = String.Format("StringID = '{0}'", stringID)
                    mcSource.InitDataForExport()
                    mcSource.Dataset.DataSetName = stringID.ToString
                    For Each oTable As DataTable In mcSource.Dataset.Tables
                        For Each oRow As DataRow In oTable.Rows
                            oRow.SetAdded()
                        Next
                    Next

                    'Bypass pour ne plus utiliser la connection par défaut
                    AppManager.IsConnected = False
                    AppManager.OverrideByPassConnectionStringTOMaster = True

                    'Indique qu'elle connection utiliser dans le App.Config
                    AppManager.ConnectionConfigName = "ConnectionToMyMaster"
                    Using mcDest As MetaStrings_PL = New MetaStrings_PL("MetaStringsExport")
                        mcDest.InitData()
                        mcDest.Dataset.Merge(mcSource.Dataset)
                        IsSaved = mcDest.Save()
                    End Using
                    Return IsSaved
                Catch ex As Exception
                    Throw ex
                Finally

                    'Remet en route la connection par défaut
                    AppManager.IsConnected = True
                    AppManager.OverrideByPassConnectionStringTOMaster = False

                    'Change pour utiliser la connection par défaut
                    AppManager.ConnectionConfigName = Nothing
                End Try
                Return False
            End Using
        End Function

        Public Shared Function ImportMetaStrings(ByVal fileName As String) As Boolean
            Using dset As DataSet = New DataSet()
                dset.ReadXml(fileName, XmlReadMode.ReadSchema)
                Using ms As MetaStrings_PL = New MetaStrings_PL("MetaStringsExport")
                    'Hack: DataSet must be fill to have adaptercommand and merge...
                    ms.InitData()
                    ms.Dataset.Merge(dset)
                    Return ms.Save()
                End Using
            End Using
        End Function

        Public Function InitDataForExport() As Boolean
            Dim metaDataTableChild As CommonExt.MetaDataTable
            Dim aChildRelationField As String
            Dim aParentRelationField As String
            Dim parentGuid As Guid = Guid.Empty

            Try
                Me.MetaDataTable.FillBusinessApplicationData()
                Me.Dataset.Tables.Add(Me.MetaDataTable)
                'ici on veux un record seulement
                If Not String.IsNullOrEmpty(Me.MetaDataTable.MetaCommand.SQLWhere) Then
                    parentGuid = CType(Me.MetaDataTable.Rows(0).Item(0), Guid)
                End If

                For Each row As DataRow In Me.MetaDataTable.MetaCommand.GetChildDisplayQuery.Rows
                    metaDataTableChild = New CommonExt.MetaDataTable() With {.QueryName = row("QueryName").ToString}

                    aChildRelationField = row("FKColumn_Name")
                    aParentRelationField = row("PKColumn_Name")
                    '
                    metaDataTableChild.GetMetaCommand()
                    '
                    If parentGuid <> Guid.Empty Then
                        metaDataTableChild.MetaCommand.SQLWhere = String.Format("{0} = '{1}'", aChildRelationField, parentGuid)
                    End If
                    '
                    metaDataTableChild.FillBusinessApplicationData()
                    '
                    Me.Dataset.Tables.Add(metaDataTableChild)
                    Dim aDR As New DataRelation(row("Relation").ToString, Me.MetaDataTable.Columns(aParentRelationField), metaDataTableChild.Columns(aChildRelationField))
                    Me.Dataset.Relations.Add(aDR)
                Next
                Return True
            Catch ex As Exception
                Throw ex
            End Try
            Return False
        End Function
        Public Overrides Sub ValidateRow(row As DataRow)
            row.ClearErrors()
            'Mandatory Fields
            'TODO: Cache MetaString in AppManager, so here we read it once maybe for nothing
            'Dim ms As MetaString
            'ms = MetaString.GetMetaStringByCode("Mandatory", AppManager.ApplicationOption.LanguageId)
            If IsDBNull(row("DefaultString")) Then
                row.SetColumnError("DefaultString", "Mandatory")
            End If
            'If IsDBNull(row("StringTypeID_FK")) Then
            '    row.SetColumnError("StringTypeID_FK", "Mandatory")
            'End If
            'Delete Commented lines below in 3 month BDesjardins 2013-09-02
            'If IsDBNull(row("TextFormatID_FK")) Then
            '    row.SetColumnError("TextFormatID_FK", "Mandatory")
            'End If

            If IsDBNull(row("Customize")) Then
                row.SetColumnError("Customize", "Mandatory")
            End If
            If IsDBNull(row("SystemRecord")) Then
                row.SetColumnError("SystemRecord", "Mandatory")
            End If

            If row.HasErrors Then
                row.RowError = "Please check your columns, a validation error occur"
            End If
        End Sub

        Sub OnRowUpdating(ByVal sender As Object, ByVal e As SqlRowUpdatingEventArgs) Handles MetaDataTable.OnRowUpdating
            If e IsNot Nothing AndAlso e.Command IsNot Nothing Then
                If e.Command.CommandText = "bsp_MetaString_PL_Save" Then
                    Me.MetaDataTable.Adapter.InsertCommand.Parameters("@GenerateSEQ").Value = SequenceGeneration
                    '
                    Me.MetaDataTable.Adapter.UpdateCommand.Parameters("@GenerateSEQ").Value = SequenceGeneration
                End If
            End If
        End Sub



        Public Function BatchRecords(dataRow() As DataRow) As Boolean Implements IPLProcess.BatchRecords
            Return True
        End Function

        Public Function CurrentRecord(dataRow As DataRow) As Boolean Implements IPLProcess.CurrentRecord
            Return True
        End Function

        Public Function NewRecord(dataRow As DataRow) As Boolean Implements IPLProcess.NewRecord

            dataRow("StringID") = Guid.NewGuid

            Return True
        End Function
    End Class
End Namespace
